package com.lmx.smsmonitor.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.lmx.smsmonitor.javamail.MailSendHelper;
import com.lmx.smsmonitor.javamail.MailSenderInfo;
import com.lmx.smsmonitor.util.Const;
import com.lmx.smsmonitor.util.SharedPreUtil;

public class SmsReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVER_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!SMS_RECEIVER_ACTION.equals(intent.getAction())) {
            return;
        }
        String format = intent.getStringExtra("format");
        StringBuilder smsContent = new StringBuilder();
        Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < messages.length; i++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    messages[i] = SmsMessage.createFromPdu(((byte[]) pdus[i]), format);
                } else {
                    messages[i] = SmsMessage.createFromPdu(((byte[]) pdus[i]));
                }
            }
            for (SmsMessage message : messages) {
                smsContent.append(message.getMessageBody());
            }
            String senderTel = messages[0].getOriginatingAddress();
            String senderAccount = (String) SharedPreUtil.getData(Const.KEY_SENDER_ACCOUNT, "");
            String senderPassword = (String) SharedPreUtil.getData(Const.KEY_SENDER_PASSWORD, "");
            String receiverAccount = (String) SharedPreUtil.getData(Const.KEY_RECEIVER_ACCOUNT, "");
            new Thread(() -> sendMail(senderAccount, senderPassword, receiverAccount, senderTel, smsContent.toString())).start();
    }

    private void sendMail(String senderAccount, String senderPassword, String receiverAccount, String tel, String content) {
        MailSenderInfo mailSenderInfo = new MailSenderInfo();
        mailSenderInfo.setMailServerHost("smtp.163.com");
        mailSenderInfo.setMailServerPort("");
        mailSenderInfo.setValidate(true);
        mailSenderInfo.setDebugMode(true);
        mailSenderInfo.setAccount(senderAccount);
        mailSenderInfo.setPassword(senderPassword);
        mailSenderInfo.setFromAddress(senderAccount);
        mailSenderInfo.setToAddress(receiverAccount);
        mailSenderInfo.setSubject("收到手机号为 " + tel + " 发来的一条短信，请查看！");
        mailSenderInfo.setContent(content);
        if (MailSendHelper.sendTextMail(mailSenderInfo)) {
            Log.i("Debug", "发送成功！");
        } else {
            Log.i("Debug", "发送失败");
        }
    }
}
